import type { IWxPhoneLogin } from '@/api/login'
import type { IUserInfoVo } from '@/api/types/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  // getUserInfo as _getUserInfo,
  login as _login,
  logout as _logout,
  wxLogin as _wxLogin,
  wxPhoneLogin as _wxPhoneLogin,
  getWxCode,
} from '@/api/login'
import apiTest from '@/api/user'
import { toast } from '@/utils/toast'

// 初始化状态
const userInfoState: IUserInfoVo = {
  id: 0,
  username: '',
  avatar: '',
  token: '',
  isMobile: '',
  authType: 0,
  createTime: 0,
  headimgurl: '',
  inviteCode: '',
  lastLoginTime: 0,
  loginName: '',
  mobile: '',
  nickname: '',
  registerType: 0,
  sex: 0,
  status: 0,
  usersId: '',
  systemInfo: {},
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<IUserInfoVo>({ ...userInfoState })
    // 设置用户信息
    const setUserInfo = (val: IUserInfoVo) => {
      console.log('设置用户信息', val)
      // 处理头像
      if (!val.headimgurl) {
        val.headimgurl = 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/avatar.png'
      }
      userInfo.value = val
    }
    const setUserAvatar = (avatar: string) => {
      userInfo.value.avatar = avatar
      console.log('设置用户头像', avatar)
      console.log('userInfo', userInfo.value)
    }
    // 删除用户信息
    const removeUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
    }
    /**
     * 获取用户信息
     */
    const getUserInfo = async () => {
      const res = await apiTest.getUserInfo()
      console.log('获取用户信息返回:', res)

      // 确保result存在
      if (res.result) {
        const userInfoData = res.result as unknown as IUserInfoVo
        setUserInfo(userInfoData)
        uni.setStorageSync('userInfo', userInfoData)
        return userInfoData
      }
      return null
    }
    /**
     * 用户登录
     * @param credentials 登录参数
     * @returns R<IUserLogin>
     */
    const login = async (credentials: {
      username: string
      password: string
      code: string
      uuid: string
    }) => {
      const res = await _login(credentials)
      console.log('登录信息', res)
      toast.success('登录成功')
      await getUserInfo()
      return res
    }

    /**
     * 退出登录 并 删除用户信息
     */
    const logout = async () => {
      // _logout()
      removeUserInfo()
    }
    /**
     * 微信登录
     */
    const wxLogin = async () => {
      // 获取微信小程序登录的code
      const data = await getWxCode()
      console.log('微信登录code', data)

      const res = await _wxLogin(data)
      await getUserInfo()
      return res
    }

    /**
     * 微信手机号登录
     * @param data 包含code、encryptedData和iv的对象
     * @returns Promise包含登录结果
     */
    const wxPhoneLogin = async (data: { mobile: string, smsCode: string, clientInfoType?: string, fromInviteCode?: string, roleType?: string }) => {
      console.log('微信手机号登录参数', data)
      const res = await apiTest.mobileLogin(data)
      console.log('微信手机号登录响应', res)

      // 如果登录成功且返回了token，立即存储
      if (res.data && res.data.token) {
        console.log('登录成功，获取到token:', res.data.token)

        // 立即存储token到本地存储
        uni.setStorageSync('token', res.data.token)

        // 更新userInfo中的token
        userInfo.value = {
          ...userInfo.value,
          token: res.data.token,
          id: Number(res.data.id),
          username: res.data.username,
        }

        // 测试token是否正确存储
        console.log('存储后检查token:', uni.getStorageSync('token'))
        console.log('存储后检查userStore:', userInfo.value)
      }

      // 获取完整用户信息
      try {
        await getUserInfo()
      }
      catch (error) {
        console.error('获取用户信息失败', error)
      }

      return res
    }
    const getSystemInfo = (): UniApp.GetSystemInfoResult => {
      const systemInfo = uni.getSystemInfoSync()
      console.log(systemInfo, 'getSystemInfo')
      userInfo.value.systemInfo = systemInfo
      return systemInfo
    }

    return {
      userInfo,
      login,
      wxLogin,
      wxPhoneLogin,
      getUserInfo,
      setUserAvatar,
      logout,
      getSystemInfo,
    }
  },
  {
    persist: true,
  },
)
